package com.jiang.jetpackdemo.fragment

import android.content.Context
import android.os.Environment
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jiang.jetpackdemo.database.RoomHelper
import com.jiang.jetpackdemo.http.RetrofitManager
import com.jiang.jetpackdemo.model.FavoritesModel
import com.jiang.jetpackdemo.model.ImgInfo
import com.jiang.jetpackdemo.utils.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.time.ZonedDateTime
import kotlin.collections.ArrayList

class PicRecommendViewModel : ViewModel() {
    val imgList: MutableLiveData<ArrayList<ImgInfo>> by lazy { MutableLiveData<ArrayList<ImgInfo>>() }
    val sizeOfimgList: MutableLiveData<Int> by lazy { MutableLiveData<Int>() }
    private lateinit var context: Context
    private val roomHelper: RoomHelper by lazy { RoomHelper(context) }
    private var job: Job? = null


    init {
        imgList.value = ArrayList()
        sizeOfimgList.value = 0
    }

    fun init(context: Context) {
        this.context = context.applicationContext
    }

    fun getData(
        isActiveRefresh: Boolean, onFinish: (() -> Unit) = {
            Log.d("PicRecommendViewModel", "onFinish callback was not used")
        }
    ) {
        imgList.value?.clear()
        job = viewModelScope.launch(Dispatchers.Main) {
            //从本地数据库获取数据，如果失败就从网络获取
            if (isActiveRefresh || !getDataFromLocalDB()) getDataFromNet(onFinish)
        }
    }

    private suspend fun getDataFromNet(onFinish: (() -> Unit)) {
        withContext(Dispatchers.IO) {
            //从接口获取十张图片
            for (i in 1..10) {
                val imgInfo = RetrofitManager.getPic()
                imgList.value?.addAndChange(imgInfo, sizeOfimgList)
                imgInfo.id = i
                roomHelper.imgInfoDao.insert(imgInfo)
            }
        }
        onFinish()
    }

    private suspend fun getDataFromLocalDB(): Boolean {
        return withContext(Dispatchers.IO) {
            val queryAll = roomHelper.imgInfoDao.queryAll()
            if (queryAll.isEmpty()) {
                return@withContext false
            } else {
                queryAll.forEach {
                    imgList.value?.addAndChange(it, sizeOfimgList)
                }
                return@withContext true
            }
        }
    }

    fun shareImage(context: Context, url: String) {
        viewModelScope.launch(Dispatchers.Main) {
            val file = if (hasSameFile(context, url, false)) {
                File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.absolutePath)
            } else {
                downloadImage(context, url)
            }
            val canShareFile = shareFile(context, file.absolutePath, true)
            Toast.makeText(context, if (canShareFile) "分享成功" else "分享失败", Toast.LENGTH_SHORT).show()
        }
    }

    fun saveAImage(url: String, onFinish: () -> Unit = {}) {
        viewModelScope.launch(Dispatchers.Main) {
            if (hasSameFile(context, url, false)) {
                Toast.makeText(context, "图片已存在", Toast.LENGTH_SHORT).show()
                onFinish()
            } else {
                saveImage(context, url, onFinish = onFinish)
                Toast.makeText(context, "保存图片成功", Toast.LENGTH_SHORT).show()
            }
        }
    }

    fun addInFavorites(imgInfo: ImgInfo) {
        viewModelScope.launch(Dispatchers.Main) {
            val favoritesModel =
                FavoritesModel(
                    null,
                    "",
                    FavoritesModel.TYPE_PICTURE,
                    "",
                    "",
                    imgInfo.imgurl,
                    timeFormatter.format(ZonedDateTime.now())
                )
            if (isAlreadyCollected(favoritesModel, roomHelper.favoritesModelDao)) {
                Toast.makeText(context, "已经收藏过了", Toast.LENGTH_SHORT).show()
            } else {
                withContext(Dispatchers.IO) {
                    roomHelper.favoritesModelDao.insert(favoritesModel)
                }
                Toast.makeText(context, "收藏成功", Toast.LENGTH_SHORT).show()
            }
        }
    }


    override fun onCleared() {
        super.onCleared()
        job?.cancel()
    }
}
